package io.github.enbool.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.github.enbool.bean.Message;
import lombok.extern.slf4j.Slf4j;

@Component
@ServerEndpoint(value = "/ws/device")
@Slf4j
public class DeviceServer {

	private static final AtomicInteger onlineCounter = new AtomicInteger(0);
	
	private static CopyOnWriteArraySet<Session> sessions = new CopyOnWriteArraySet<>();
	private ObjectMapper objectMapper = new ObjectMapper();
	// (ObjectMapper) ContextLoader.getCurrentWebApplicationContext().getBean("objectMapper");
	
	@OnOpen
	public void onOpen(Session session) {
		sessions.add(session);
		int counter = onlineCounter.incrementAndGet();
		log.info("新建连接，当连接数：{}", counter);
		
		sendMessage(session, "");
	}
	
	@OnClose
	public void onClose(Session session) {
		sessions.remove(session);
		
		int counter = onlineCounter.decrementAndGet();
		log.info("{}关闭连接，当连接数：{}", session.getId(), counter);
	}
	
	@OnMessage
	public void onMessage( String message, Session session) throws JsonParseException, JsonMappingException, IOException {
		Message msg = objectMapper.readValue(message, Message.class);
		
		log.info("来自{}的消息：{} --{}", session.getId(),msg.getDeviceId(), msg.getUses());
		CustomerServer.sendAll(message);
	}
	
	@OnError
	public void onError(Session session, Throwable error) {
		log.info("客户端[{}]发送错误{}", session.getId(), error.getMessage());
	}
	
	public static void sendMessage(Session session, String message) {  
        try {  
            session.getBasicRemote().sendText(message);  
        } catch (IOException e) {  
            log.error("发送消息出错：{}", e.getMessage());  
            e.printStackTrace();  
        }  
    }  
	
	public static void sendAll(String message) {
		for(Session session: sessions) {
			sendMessage(session, message);
		}
	}
}

